package com.shen.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo02 {
    public static void main(String[] args) {
        Phone2 phone = new Phone2();

        new Thread(()->{
            phone.sms();
        },"A").start();

        new Thread(()->{
            phone.sms();
        },"B").start();

        /**
         * A SMS~
         * A Call~
         * B SMS~
         * B Call~
         */
    }
}

class Phone2{
    Lock lock=new ReentrantLock();
    public  void sms(){
        /**
         * 加锁和解锁必须是一对一的，不能有一个少掉
         * 如果只有加锁没有解锁，会出现死锁的情况，线程想出去的时候没有钥匙，就会一直停在那
         */
        lock.lock();//加锁
        lock.lock();//加锁 没有解锁，会出先死锁
        try {
            System.out.println(Thread.currentThread().getName()+" SMS~");
            call();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }

    }
    public  void call(){
        lock.lock();//加锁
        try {
            System.out.println(Thread.currentThread().getName()+" Call~");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//解锁
        }
    }
}
